/*
Java source file
Copyright: Umschalt.com 2012
*/
package com.david.documentation.service.indexer;

import com.david.documentation.domain.entities.doku.Doku;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.Version;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
import org.hibernate.search.jpa.Search;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Service(value = "indexerService")
@Transactional(rollbackFor = Exception.class)
public class IndexerServiceImpl implements IndexerService {

	@PersistenceContext
    private EntityManager entityManager;

	private FullTextSession fullTextSession;

	public List<Doku> startIndexer(String searchTerms, Integer startIndex, Integer maxResults) {


		FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
		String[] fieldsZoMatch = new String[]{"name","description"};
		QueryParser parser = new MultiFieldQueryParser(Version.LUCENE_30,fieldsZoMatch,new StandardAnalyzer(Version.LUCENE_30));
		Query luceneQuery = null;

		try {
			luceneQuery = parser.parse(searchTerms);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		FullTextQuery jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, Doku.class);

		if (startIndex != null && maxResults != null){
			jpaQuery.setFirstResult(startIndex);
			jpaQuery.setMaxResults(maxResults);
		}

		List<Doku> dokuList = jpaQuery.getResultList();

		return dokuList;
	}


	
}
